<script setup lang="ts">
import { ref, watch, nextTick } from "vue";
import ChooseMaterialDialog from "@/components/ChooseMaterialDialog";
import { storeToRefs } from "pinia";
import { useSystemStoreWithOut } from "@/store/modules/system";
import { useMessage } from "@/hooks/useMessage";
import { sub, add } from "@/utils/caculate";
import { getOutboundQueryMaterialStock } from "@/api/outbound";

const ADD_LINE_HEIGHT = 40; // 添加行高度
const ROW_HEIGHT = 55; // table单行高度
const MAX_NUM = 9999999;
const { createConfirm, createNotification } = useMessage();
const systemStore = useSystemStoreWithOut();
const props = defineProps({
  list: {
    type: Array,
    default: () => []
  },
  tableHeight: {
    type: Number,
    default: 0
  },
  preWarehouseCode: {
    type: [String, Number],
    default: ""
  }
});

const diyRow = {
  materialCode: "", // 物料编码
  materialSpecsId: "", // 物料规格id
  materialName: "", // 物料名称
  materialType: "", // 物料类型
  materialSpecs: "", // 物料规格
  unit: "", // 单位
  overReceiveFlag: 0, // 超领标志
  maxNum: 0, // 最大可出库数量
  num: 0, // 本次出库数量
  overReceiveNum: 0, // 超领数量
  overReceiveWarehouseCode: "" // 超额处置仓库
};

const emits = defineEmits(["setTotalData"]);

const tableData = ref([]);
const curRow = ref({});
const curRowIndex = ref(null);
const tableRef = ref(null);
const editMaterialRef = ref();
const { warehouseList, materialTypeList } = storeToRefs(systemStore);

watch(
  () => props.list,
  (newVal: any) => {
    tableData.value = newVal;
  },
  { deep: true }
);

watch(
  tableData,
  (newVal: any) => {
    emits("setTotalData", newVal);
  },
  { deep: true }
);

watch(
  () => props.preWarehouseCode,
  (newVal: any, oldVal: any) => {
    if (!oldVal) return;
    tableData.value = [];
    curRow.value = {};
    curRowIndex.value = null;
  }
);

const handleRowClick = (row: any) => {
  curRow.value = row;
};

const addRow = () => {
  tableData.value.push(diyRow);
};

/**
 * 选择物料
 */
const chooseMaterial = (row: any, i: number) => {
  if (!props.preWarehouseCode) {
    createNotification({
      message: "请先选择出库仓库名称",
      type: "error"
    });
    return;
  }
  curRow.value = row;
  curRowIndex.value = i;
  editMaterialRef.value.open();
};

/**
 * 删除行
 */
const handleDeleteRow = (i: number) => {
  createConfirm({
    message: "确定删除该行吗？",
    center: false
  }).then(() => {
    tableData.value.splice(i, 1);
  });
};

// 添加物料
const addMaterial = (selections: any) => {
  const results = selections.map(val => {
    return {
      materialCode: val.materialCode,
      materialSpecsId: val.materialSpecsId,
      warehouseCode: props.preWarehouseCode
    };
  });
  getOutboundQueryMaterialStock(results).then(rsp => {
    const res = rsp.data || [];
    res.unshift(curRowIndex.value, 1);
    Array.prototype.splice.apply(tableData.value, res);
    nextTick(() => {
      tableRef.value.setScrollTop(
        add(curRowIndex.value, res.length) * ROW_HEIGHT
      );
    });
  });
};

defineExpose({
  getTableData: () => {
    return tableData.value;
  }
});
</script>

<template>
  <div>
    <el-table
      ref="tableRef"
      class="tableBox"
      :data="tableData"
      style="width: 100%"
      :height="tableHeight - ADD_LINE_HEIGHT"
      @row-click="handleRowClick"
    >
      <el-table-column type="index" label="序号" min-width="100px" />
      <el-table-column
        prop="materialCode"
        label="物料编码"
        min-width="104px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="materialName"
        label="物料名称"
        min-width="160px"
        show-overflow-tooltip
      />
      <el-table-column
        label="物料类型"
        prop="materialType"
        min-width="104px"
        show-overflow-tooltip
      >
        <template #default="scope">
          <el-text>{{
            materialTypeList.find(
              val => val.dictLabelValue == scope.row.materialType
            )?.dictLabelName
          }}</el-text>
        </template>
      </el-table-column>
      <el-table-column
        prop="materialSpecs"
        label="物料规格"
        min-width="160px"
        show-overflow-tooltip
      >
        <template #default="scope">
          <el-text>{{
            scope.row.materialSpecsName || scope.row.materialSpecs
          }}</el-text>
        </template>
      </el-table-column>
      <el-table-column
        prop="unit"
        label="单位"
        min-width="80px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="instockNum"
        label="可用库存"
        min-width="104px"
        align="center"
      >
        <template #default="{ row }">
          <el-text>{{ row.instockNum || "-" }}</el-text>
        </template>
      </el-table-column>
      <el-table-column
        prop="maxNum"
        label="最大可出库数量"
        min-width="152px"
        align="center"
      >
        <template #default="{ row }">
          <el-text>{{ row.maxNum || "-" }}</el-text>
        </template>
      </el-table-column>
      <el-table-column prop="num" label="本次出库数量" min-width="152px">
        <template #default="{ row }">
          <el-input-number
            v-model="row.num"
            placeholder="请输入内容"
            :controls="false"
            :max="row.overReceiveFlag ? MAX_NUM : row.maxNum || MAX_NUM"
            :min="0"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="overReceiveNum"
        label="超领数量"
        min-width="152px"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{
            row.overReceiveFlag
              ? sub(row.num, row.maxNum) < 0
                ? 0
                : sub(row.num, row.maxNum)
              : 0
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="overReceiveWarehouseCode"
        label="超额处置仓库"
        min-width="152px"
      >
        <template #default="scope">
          <el-select
            v-model="scope.row.overReceiveWarehouseCode"
            :disabled="!scope.row.overReceiveNum"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="(item, index) in warehouseList"
              :key="index"
              :value="item.warehouseCode"
              :label="item.warehouseName"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        align="left"
        min-width="166px"
      >
        <template #default="{ row, $index }">
          <el-button type="primary" link @click="chooseMaterial(row, $index)"
            >选择物料
          </el-button>
          <el-button type="danger" link @click="handleDeleteRow($index)"
            >删除行</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div
      class="addRow cursor-pointer text-center leading-[30px] h-[30px] border border-solid outline-[#eeeeee] mt-[10px] rounded-[4px]"
      @click="addRow"
    >
      <span class="text-[14px]">+ 添加行</span>
    </div>
    <ChooseMaterialDialog ref="editMaterialRef" @submit="addMaterial" />
  </div>
</template>
<style scoped lang="scss">
.addRow {
  overflow: hidden;
  user-select: none;
  &:hover {
    color: $main-color;
  }
}
</style>
